package br.com.future.dao;

import java.sql.Types;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import br.com.future.domain.User;

public class FutureDao {

	private static final String RETRIEVE_ALL_USERS = "SELECT user.* FROM future.user user";
	private static final String LOGIN_REQUEST = "SELECT COUNT(*) FROM future.user user WHERE user.login = ? AND user.passwd = ?";
	private static final String INSERT_USER_SQL = "INSERT INTO future.user (name, email, login, passwd) values (?, ?,?,?)";
	private static final Log LOG = LogFactory.getLog(FutureDao.class);
	private SimpleJdbcTemplate jdbcTemplate;

	public FutureDao() {
		jdbcTemplate = null;
	}
	
	public boolean checkCredentials (String username, String passwd) {
		try {
			int credentialsPass =  this.jdbcTemplate.queryForInt(LOGIN_REQUEST, 
					new SqlParameterValue(Types.VARCHAR, username),
					new SqlParameterValue(Types.VARCHAR, passwd));

			if (1 == credentialsPass)
				return true;
		} catch (DataAccessException e) {
			LOG.error("Error while check user credentials.", e);
		}
		return false;
	}

	public void persistUser(User user) {
		if (user == null)
			throw new RuntimeException("Empty user - Unable to persist.");
		try {
			this.jdbcTemplate.update(INSERT_USER_SQL, 
					new SqlParameterValue(Types.VARCHAR, user.getName()),
					new SqlParameterValue(Types.VARCHAR, user.getEmail()),
					new SqlParameterValue(Types.VARCHAR, user.getLogin()),
					new SqlParameterValue(Types.VARCHAR, user.getPasswd()));
		} catch (DataIntegrityViolationException e) {
			LOG.error("Duplicate user.", e);
			throw new RuntimeException("Duplicate user.");
		}
	}

	public List<User> getUsers() {
		return this.jdbcTemplate.query(RETRIEVE_ALL_USERS, new UserMapper());
	}

	/**
	 * @param jdbcTemplate the jdbcTemplate to set
	 */
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = new SimpleJdbcTemplate(jdbcTemplate);
	}
}
